<?php
class hschool_course_choose{
	public $info_array = array();
	public $page_array = array();
	public $tree_array = array();

	static function &instance() {
		static $object;
		if(empty($object)) {
			$object = new self();
		}
		return $object;
	}

	/*
	*	取出一个选课信息
	*/
	public function get_one($id='') {
		$info = array();
		if($id){
			$sql = "SELECT * FROM ".DB::table('student_course')." WHERE id='".$id."'";
			$info = DB::fetch_first($sql);	
		}
		return $info;
	}

	/*
	*	取出所有已选课人员数组
	*/
	public function get_all($id='') {
		$info = array();
		if($id){
			$sql = "SELECT uid FROM ".DB::table('student_course')." WHERE course_id='".$id."'";
			$result = DB::fetch_all($sql);
			foreach($result AS $key => $value){
				$info[$value['uid']]=$value['uid'];
			}
		}
		return $info;
	}
    /*
	*	CSV 批量选课
	*/
    public function csv_add(){
        global $_G;
        if(3==$_G['user_role_id'] || 31==$_G['user_role_id'] || 41==$_G['user_role_id'] || 42==$_G['user_role_id']){
            $is_submit = isset($_REQUEST['is_submit']) ? $_REQUEST['is_submit']:'';
            $csv_add_file = isset($_REQUEST['csv_add_file']) ? $_REQUEST['csv_add_file']:'';
            if(!empty($is_submit) && !empty($csv_add_file)){
                if(file_exists(SITE_ROOT.$csv_add_file)){
                    $csv_add_file_path = SITE_ROOT.$csv_add_file;
                    $csv_add_file_path_array = explode('/',$csv_add_file_path);
                    $csv_name = $csv_add_file_path_array[8];
                    $csv_add_file_path_folder = $csv_add_file_path_array[0].'/'.$csv_add_file_path_array[1].'/'.$csv_add_file_path_array[2].'/'.$csv_add_file_path_array[3].'/'.$csv_add_file_path_array[4].'/'.$csv_add_file_path_array[5].'/'.$csv_add_file_path_array[6].'/'.$csv_add_file_path_array[7].'/';
                    $csv = new csv($csv_name, '', '', $csv_add_file_path_folder);
                    $input_info = $csv->csv_to_array();
                    unset($input_info[0]);
                    $student_user_name = array();
                    $student_user_course = array();
                    $choose_num=0;
                    $student_num=array();
                    foreach($input_info AS $key => $value){
                        //DEBUG 查询用户是否存在 如果存在就导入
                        $check_user_id_exist = DB::result_first("SELECT user_id FROM ".DB::table('users')." WHERE user_name = '".$value['1']."' AND isdelete=0 LIMIT 1");
                        if($check_user_id_exist && !empty($value[2])){
                            $student_num[$check_user_id_exist]=$check_user_id_exist;
                            //执行导入
                            $course_id_array_tmp = explode(',',$value[2]);
                            $course_id_array = array();
                            foreach($course_id_array_tmp AS $k=>$v){
                                $course_id_array[$v]=$v;
                            }
                            if(!empty($course_id_array) && is_array($course_id_array)){
                                //DEUBG 过滤用户已选课程
                                $get_student_course = DB::fetch_all("SELECT course_id,uid,course_flag FROM ".DB::table('student_course')." WHERE uid ='".$check_user_id_exist."' AND course_cate='".$value[0]."'");
                                if(!empty($get_student_course)){
                                    foreach($get_student_course AS $kk => $vv){
                                        if($vv['course_flag'] != 1){
                                            //DEBUG 删除原选课
                                            $sql_other = "DELETE FROM ".DB::table('student_course')." WHERE course_id='".$vv['course_id']."' AND  uid='".$vv['uid']."' AND  course_flag='0' LIMIT 1";
                                            @DB::query($sql_other);
                                            //@DB::delete('student_course',array('course_id'=>$vv['course_id'],'uid'=>$vv['uid'],'course_flag'=>0),1);
                                        }
                                        if($vv['course_flag'] == 1){
                                            unset($course_id_array[$vv['course_id']]);
                                        }
                                    }
                                }
                                //DEBUG 执行插入选课表与订单记录表
                                foreach($course_id_array AS $kkk=>$vvv){
                                    if(1==$value[0]){
                                        $action_course_path = libfile('hschool/course', 'class/admin','..');
                                        if(file_exists($action_course_path)){
                                            require_once $action_course_path;
                                            $hschool_course = new hschool_course();
                                            $course_info = $hschool_course->get_one($vvv);
                                        }   
                                    }
                                    if(2==$value[0]){
                                        $action_course_path = libfile('hschool/vod', 'class/admin','..');
                                        if(file_exists($action_course_path)){
                                            require_once $action_course_path;
                                            $hschool_course = new hschool_vod();
                                            $course_info = $hschool_course->get_one($vvv);
                                        }   
                                    }
                                    //DEBUG 插入交易记录
                                    $trade_status = 'TRADE_SUCCESS';
                                    $data_trade = array(
                                        "user_id"=>$check_user_id_exist,
                                        "trade_type"=>1,
                                        "trade_opt_id"=>'1',
                                        "out_trade_no"=>'0512'.date('YmdHis').rand(1000,9999),
                                        "total_fee"=>$course_info['price'],
                                        "trade_status"=>$trade_status,
                                        "create_dateline"=>TIMESTAMP,
                                        "first_trade_success_time"=>TIMESTAMP,
                                        "trade_way"=>2,
                                    );
                                    $insert_id_trade = @DB::insert('trade',$data_trade,true);
                                    $data_trade['trade_id']=$insert_id_trade;
                                    $insert_id_trade_log = @DB::insert('trade_log',$data_trade,true);
                                    $data = array(
                                        "uid"=>$check_user_id_exist,
                                        "course_id"=>$vvv,
                                        "course_flag"=>1,
                                        "course_price"=>$course_info['price'],
                                        "dateline"=>TIMESTAMP,
                                        "trade_id"=>$insert_id_trade,
                                        "applicant"=>$_G['user_id'],
                                        "course_cate"=>$value[0]
                                    );
                                    $insert_id = DB::insert('student_course',$data,true);
                                    if($insert_id){
                                        $choose_num++;
                                    }
                                }
                            }
                        }
                    }
                    //DEBUG 找出所有用户名并导入
                    $this->return_json(true,'总导入选课'.$choose_num.'人次,发现学生人数'.count($student_num),array('csv_add_file'=>$csv_add_file));
                }else{
                    $this->return_json(true,'未发现导入文件',array('csv_add_file'=>$csv_add_file));
                }
                die;
            }
            include template('admin/hschool/course_choose_csv_add');
        }else{
            echo "您无选线操作";
        }
    }
	/*
	*	人工选课
	*/
	public function add($pos='admincp') {
		global $_G;
		set_time_limit(0);
		ini_set('memory_limit', '512M');
		$is_submit = isset($_REQUEST['is_submit']) ? $_REQUEST['is_submit']:'';
		$id = isset($_REQUEST['id']) ? $_REQUEST['id']:'';
		$hand = isset($_REQUEST['hand']) ? $_REQUEST['hand']:'';
		if(!empty($is_submit) && !empty($id)){
			$student_course_choose = isset($_REQUEST['student_course_choose']) ? trim($_REQUEST['student_course_choose']):'';
			if(!empty($student_course_choose)){
				$choose_num = 0;
				$student_course_choose_array = explode(',',$student_course_choose);
				$student_course_choose_count = count($student_course_choose_array);
				//DEBUG 取出本课程已选课人员
				$student_course_choosed=$this->get_all($id);
				$student_course_choosed_count = count($student_course_choosed);
				$course_flag = isset($_REQUEST['course_flag']) ? $_REQUEST['course_flag']:0;
                $course_cate = isset($_REQUEST['course_cate']) ? $_REQUEST['course_cate']:'';
                if(1==$course_cate){
                    $action_course_path = libfile('hschool/course', 'class/admin','..');
                    if(file_exists($action_course_path)){
                        require_once $action_course_path;
                        $hschool_course = new hschool_course();
                        $course_info = $hschool_course->get_one($id);
                    }   
                }
                if(2==$course_cate){
                    $action_course_path = libfile('hschool/vod', 'class/admin','..');
                    if(file_exists($action_course_path)){
                        require_once $action_course_path;
                        $hschool_course = new hschool_vod();
                        $course_info = $hschool_course->get_one($id);
                    }   
                }
				foreach($student_course_choose_array AS $key => $value){
					if(!in_array($value,$student_course_choosed)){
						//DEBUG 插入交易记录
						if(1==$course_flag){
							$trade_status = 'TRADE_SUCCESS';
						}elseif(2==$course_flag){
							$trade_status = 'TRADE_FREE';
						}else{
							$trade_status = 'WAIT_BUYER_PAY';
						}
						$data_trade = array(
							"user_id"=>$value,
							"trade_type"=>1,
							"trade_opt_id"=>$id,
							"out_trade_no"=>'0512'.date('YmdHis').rand(1000,9999),
							"total_fee"=>$course_info['price'],
							"trade_status"=>$trade_status,
							"create_dateline"=>TIMESTAMP,
                            "first_trade_success_time"=>TIMESTAMP,
							"trade_way"=>2,
						);
						$insert_id_trade = @DB::insert('trade',$data_trade,true);
						$data_trade['trade_id']=$insert_id_trade;
						$insert_id_trade_log = @DB::insert('trade_log',$data_trade,true);
						$data = array(
							"uid"=>$value,
							"course_id"=>$id,
							"course_flag"=>$course_flag,
							"course_price"=>$course_info['price'],
							"dateline"=>TIMESTAMP,
							"trade_id"=>$insert_id_trade,
                            "applicant"=>$_G['user_id'],
                            "course_cate"=>$course_cate
						);
						$insert_id = DB::insert('student_course',$data,true);
						if($insert_id){
							$choose_num++;
						}
					}
                    if(1==$course_cate){
                        //DEBUG 更新数据库 资料费
                        @DB::insert("user_shipping",array('user_id'=>$value,'us_value'=>$_G['setting']['system_shopping_value']));   
                    }
				}
				//DEBUG 判断是否存在重复选课人员
				$already_choosed = 0;
				$already_choosed_notice = '';
				$already_choosed = $student_course_choose_count - $choose_num;
				if($already_choosed){
					$already_choosed_notice = ', 过滤重复选课'.$already_choosed.'人';
				}
				//DEBUG 总计选课人数
				$sqlcount = "SELECT count(*) from ".DB::table('student_course')." WHERE course_id='".$id."' AND course_flag=1 AND course_cate='".$course_cate."'";
				$choosed_all = DB::result_first($sqlcount);
				if($choosed_all){
					$choosed_all_notice = ', 总计选课已支付人数'.$choosed_all.'人';
					//DEBUG 更新课程的选课人数
					@DB::update('course',array('count'=>$choosed_all),array('id'=>$id));
				}
				$this->return_json(false,'成功选课,新增选课人数为'.$choose_num.'人'.$already_choosed_notice.$choosed_all_notice,array('id'=>$id,'hand'=>$hand));
			}else{
				$this->return_json(true,'未接收到选课学生',array('id'=>$id));
			}
		}else{
			if(!empty($id)){
				$hschool_course = load_class('hschool','course');
				$info = $hschool_course->get_one($id);
			}
            if('front'==$pos){
                include template('trade/add');
            }else{
                include template('admin/hschool/course_choose_add');
            }
		}
	}
    
    public function add_stu(){
        global $_G;
		set_time_limit(0);
		ini_set('memory_limit', '512M');
		$is_submit = isset($_REQUEST['is_submit']) ? $_REQUEST['is_submit']:'';
		$user_id = isset($_REQUEST['user_id']) ? $_REQUEST['user_id']:'';
        if($user_id){
            $info['user_realname'] = ext::user_realname($user_id);
        }
        if(!empty($is_submit)){
            $user_id = isset($_REQUEST['user_id']) ? $_REQUEST['user_id']:'';
            $course_id = isset($_REQUEST['course_id']) ? $_REQUEST['course_id']:'';
            $course_flag = isset($_REQUEST['course_flag']) ? $_REQUEST['course_flag']:'';
            if(!empty($course_id)){
                //DEBUG 课程去重
                $course_id = array_unique($course_id);
            }
            if(empty($user_id) || empty($course_id)){
                $this->return_json(true,'填写信息不完整,请重新提交');
            }else{
                //DEBUG 判断选课学生是否存在
                $sql = "SELECT user_id FROM ".DB::table('users')." WHERE user_id='".$user_id."' AND isdelete=0 LIMIT 1";
                $result = DB::result_first($sql);
                if(empty($result)){
                    $this->return_json(true,'选课学生微课号不存在,请核对后重新提交');
                }else{
                    $choose_num=0;
                    foreach($course_id AS $key => $value){
                        //DEBUG 判断课程是否已经选过 或 未支付状态
                        $sql = "SELECT id FROM ".DB::table('student_course')." WHERE course_id='".$value."' AND uid='".$user_id."' LIMIT 1";
                        $result = DB::result_first($sql);
                        if(empty($result)){
                            //DEBUG 购买时课程价格
                            $action_course_path = libfile('hschool/course', 'class/admin','..');
                            if(file_exists($action_course_path)){
                                require_once $action_course_path;
                                $hschool_course = new hschool_course();
                                $course_info = $hschool_course->get_one($value);
                            }
                            //DEBUG 插入交易记录
                            if(1==$course_flag){
                                $trade_status = 'TRADE_SUCCESS';
                            }elseif(2==$course_flag){
                                $trade_status = 'TRADE_FREE';
                            }else{
                                $trade_status = 'WAIT_BUYER_PAY';
                            }
                            $data_trade = array(
                                "user_id"=>$user_id,
                                "trade_type"=>1,
                                "trade_opt_id"=>$value,
                                "out_trade_no"=>'0512'.date('YmdHis').rand(1000,9999),
                                "total_fee"=>$course_info['price'],
                                "trade_status"=>$trade_status,
                                "create_dateline"=>TIMESTAMP,
                                "trade_way"=>2
                            );
                            $insert_id_trade = @DB::insert('trade',$data_trade,true);
                            $data_trade['trade_id']=$insert_id_trade;
                            $insert_id_trade_log = @DB::insert('trade_log',$data_trade,true);
                            $data = array(
                                "uid"=>$user_id,
                                "course_id"=>$value,
                                "course_flag"=>$course_flag,
                                "course_price"=>$course_info['price'],
                                "dateline"=>TIMESTAMP,
                                "trade_id"=>$insert_id_trade,
                                "applicant"=>$_G['user_id']
                            );
                            $insert_id = DB::insert('student_course',$data,true);
                            if($insert_id){
                                $choose_num++;
                            }
                            //DEBUG 更新数据库 资料费
                            @DB::insert("user_shipping",array('user_id'=>$user_id,'us_value'=>$_G['setting']['system_shopping_value']));
                        }
                    }
                    $this->return_json(false,'操作成功,已新增选课'.$choose_num.'门');
                }
            }
        }else{
           include template('admin/hschool/course_choose_add_stu'); 
        }
    }

	/*
	*	编辑课程
	*/
	public function edit() {
		global $_G;
		$is_submit = isset($_REQUEST['is_submit']) ? $_REQUEST['is_submit']:'';
		if(!empty($is_submit)){

		}else{
			$id = isset($_REQUEST['id']) ? $_REQUEST['id']:'';
			$info = $this->get_one($id);
			include template('admin/hschool/course_choose_edit');
		}
	}

	/*
	*	删除课时
	*/
	public function del() {
		$is_submit = isset($_REQUEST['is_submit']) ? $_REQUEST['is_submit']:'';
		if(!empty($is_submit)){
			$id = isset($_REQUEST['id']) ? $_REQUEST['id']:'';
			if($id){
				$where = array(
					'id'=>$id
				);
				$effects = DB::delete('student_course',$where,1);
				if($effects){
					//DEBUG 接收用户信息 end
					$this->return_json(false,'操作成功');
				}else{
					$this->return_json();
				}
			}
		}
	}

	/*
	*	删除课时
	*/
	public function set_course_flag() {
		$is_submit = isset($_REQUEST['is_submit']) ? $_REQUEST['is_submit']:'';
		if(!empty($is_submit)){
			$id = isset($_REQUEST['id']) ? $_REQUEST['id']:'';
			$course_flag = isset($_REQUEST['course_flag']) ? $_REQUEST['course_flag']:0;
			if($id && '' != $course_flag){
				$data = array(
					"course_flag"=>$course_flag
				);
				$where = array(
					'id'=>$id
				);
				$effects = DB::update('student_course',$data,$where);
				if($effects){
					//DEBUG 接收用户信息 end
					$this->return_json(false,'操作成功');
				}else{
					$this->return_json();
				}
			}
		}
	}

	/*
	*	当前动作的首页
	*/
	public function index() {
		global $_G;
		$page_array = array();
		$sqlcount = $sql = $wheresql = $title_keyword = $pageNum = $numPerPage = '';
		$pageNum = isset($_REQUEST['pageNum']) ? $_REQUEST['pageNum'] : 1;
		$numPerPage = isset($_REQUEST['numPerPage']) ? $_REQUEST['numPerPage'] : 10;
		$pagestart = ($pageNum - 1) * $numPerPage;
		$id = isset($_REQUEST['id']) ? $_REQUEST['id']:'';
		//$hschool_course = load_class('hschool','course');
		//$course_info = $hschool_course->get_one($id);
		$sqlcount = "SELECT count(*) from ".DB::table('student_course')." WHERE course_id='".$id."' ".$wheresql;
		$pagetotal = DB::result_first($sqlcount);
		$sql = "SELECT * FROM ".DB::table('student_course')." WHERE course_id='".$id."' ".$wheresql." ORDER BY id DESC LIMIT ".$pagestart.",".$numPerPage;
		$page_array = DB::fetch_all($sql);
        foreach($page_array AS $key => $value){
            if($page_array[$key]['applicant']){
                $page_array[$key]['applicant_user_realname']=ext::user_realname($value['applicant']);
            }else{
                $page_array[$key]['applicant_user_realname']=ext::user_realname($value['uid']);
            }
        }
		//总页数
		$realpages = @ceil($pagetotal / $numPerPage);
		if($realpages <= 0){
			$realpages=1;
		}
		//前一页
		$page_pre = max(1, intval(($pageNum-1)));
		//后一页
		$page_next = min(intval(($pageNum+1)), $realpages);
		include template('admin/hschool/course_choose');
	}

	/*
	* ajax 返回信息
	*/
	public function return_json($error='true',$message="操作失败",$date=array()) {
		$return_array = array(
			"error" => $error,
			"message" => $message,
			"data" => $date
		);
		echo json_ext($return_array);
		die;
	}
}
?>